package service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import constant.Constant;
import dao.UserDao;
import entity.GoldPoints;
import entity.User;
import exception.DataAccessException;
import exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.GoldPointsService;
import service.UserService;
import util.Check;
import util.DateUtil;
import util.ParameterUtil;
import vo.UserBackVo;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author Shao Liwei
 * @date 2021/1/11 14:28
 * description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    GoldPointsService goldPointsService;

    @Override
    public PageInfo<User> queryAllUsers(HttpServletRequest request) {
        String pageNo = request.getParameter("pageNo");
        UserBackVo userVo = new UserBackVo();
        userVo.setLogin_name(request.getParameter("login_name"));
        userVo.setNickname(request.getParameter("nickname"));
        userVo.setRole(request.getParameter("role"));
        userVo.setEmail(request.getParameter("email"));
        userVo.setCreate_start_date(request.getParameter("create_start_date"));
        userVo.setCreate_end_date(request.getParameter("create_end_date"));
        userVo.setLogin_start_date(request.getParameter("login_start_date"));
        userVo.setLogin_end_date(request.getParameter("login_end_date"));
//        分页处理
        System.out.println("=================="+pageNo);
        if (pageNo == "" || pageNo == null) {
            pageNo = "1";
        }
        PageHelper.startPage(Integer.parseInt(pageNo), Constant.PAGE_SIZE);

        List<User> list = userDao.queryUsers(userVo);
        return new PageInfo<User>(list);
    }

    @Override
    public User queryUser(HttpServletRequest request) {
        String id = request.getParameter("id");
        User user = userDao.queryUserById(id);
        return user;
    }

    @Override
    public String changeUsers(HttpServletRequest request) {
        String id = request.getParameter("id");
        String status = request.getParameter("status");
        if (status!="" && status !=null){
            int flag = userDao.changeStatus(id, status);
            return ((flag > 0) ? "修改成功" : "修改失敗");
        }
        String nickname = request.getParameter("nickname");
        String role = request.getParameter("role");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        int result = userDao.changeUser(id,nickname,role,password,email);
        return ((result > 0) ? "修改成功" : "修改失敗");
    }

    @Override
    public int loginBack(HttpServletRequest request) {
        String password = request.getParameter("password");
        String loginName = request.getParameter("login_name");
        String role = Constant.USER_ROLE_ADMIN;
        int flag = userDao.loginBack(loginName, password);
        if (flag > 0) {
            User user = userDao.queryUser(loginName, password,role);
            request.getSession().setAttribute(Constant.SESSION_USER, user);
        }
        return flag;
    }

    //    判断是否需要签到
    @Override
    public User findLoginDate(User user) throws ServiceException {
        //  需要重新签到
        if (null == user.getLogin_date() || DateUtil.isNeedSign(user.getLogin_date())) {
            user.setLogin_date(new Date(0));
        }
        return user;
    }

    //    登录
    @Override
    public User login(String login_name, String password) throws ServiceException {
        User user = null;
        try {
            System.out.println("service--checkPasswordByLName");
//        登录名具有唯一性，如果查不到则表示该用户没注册
            user = userDao.selectByLoginName(login_name);

            if (null == user) {
                throw new ServiceException("登录名错误！");
            }
            if (!user.getPassword().equals(password)) {
                System.out.println("password=" + password);
                System.out.println("result.getPassword()=" + user.getPassword());
                throw new ServiceException("登录密码错误，请重新登录！");
            }
            if (Constant.STATUS_DISABLE == user.getStatus()) {
                throw new ServiceException("该用户已被禁用！");
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return user;
    }


    // 可用是true，不可用是false
//    登录名称不能重复，字母、数字、下划线
    @Override
    public boolean checkLoginName(String login_name) throws ServiceException {
        boolean result = false;
        try {
            if (!Check.checkLoginName(login_name)) {
                throw new ServiceException("登录名只能包含字母、数字、下划线");
            }
            if (null != userDao.selectByLoginName(login_name)) {
                throw new ServiceException("该登录名已被占用！");
            }
            result = true;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        System.out.println("name_result=" + result);
        return result;
    }

    @Override
    public boolean checkEmail(String email) throws ServiceException {
        System.out.println("service--email");
        boolean result = false;
        try {
            if (!Check.checkEmail(email)) {
                throw new ServiceException("邮箱格式有误！");
            }
            if (null != userDao.selectByEmail(email)) {
                throw new ServiceException("该邮箱已被占用！");
            }
            result = true;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    //    用户注册
    @Override
    public boolean registUser(User user) throws ServiceException {
        System.out.println("service--registUser");
        boolean result = false;
        try {
            if (1 != userDao.insertUser(user)) {
                throw new ServiceException("注册失败！");
            }
            result = true;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    //  修改最近一次登录的日期：login_date，并为对应客户添加积分
    @Transactional
    @Override
    public boolean updateLoginDate(Integer id) throws ServiceException {
        try {
            User user = userDao.selectById(id);
            if (null == user) {
                throw new ServiceException("用户不存在！");
            }
            Date login_date = new Date();

            //  可以签到
            if (null == user.getLogin_date() || DateUtil.isNeedSign(user.getLogin_date())) {
//            修改登录日期
                userDao.updateLoginDateById(id, login_date);
//            添加积分
                goldPointsService.addSignIn(id, login_date);
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    //    修改用户信息
    @Override
    public boolean changeUser(User user) throws ServiceException {
        try {
            User oldUser = userDao.selectById(user.getId());
            if (null == oldUser) {
                throw new ServiceException("用户不存在！");
            }

            // 判断参数是否合法
            if (ParameterUtil.isNull(user.getNickname())) {
                throw new ServiceException("昵称格式有误！");
            }
            User emailUser = userDao.selectByEmail(user.getEmail());
            if (!Check.checkEmail(user.getEmail())) {
                throw new ServiceException("邮箱格式有误！");
            }
            if (null != userDao.selectByEmail(user.getEmail()) && emailUser.getId() != user.getId()) {
                throw new ServiceException("该邮箱已被占用！");
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
//        修改信息
        boolean result = false;
        try {
            if (1 != userDao.updateUserById(user)) {
                throw new ServiceException("修改信息失败！");
            }
            result = true;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public User selectDetailGPById(int id) throws ServiceException {
        User user = userDao.selectDetailGPById(id);
        //计算金币/积分总数量；
        Set<GoldPoints> gps = user.getGps();
        //遍历HashSet
        Iterator<GoldPoints> iterator=gps.iterator();
        int gold_count=0;
        int point_count=0;
        while (iterator.hasNext()){
            GoldPoints gp = iterator.next();
            gold_count += gp.getGold_count();
            point_count += gp.getPoint_count();
        }
        user.setGold_count(gold_count);
        user.setPoint_count(point_count);
        return user;
    }
}
